package net.flintx.array;

import java.util.Arrays;
import java.util.HashMap;

/**
 * Created by flintx on 2018/1/9.
 */
public class TwoSum2 {
    public int[] twoSum(int[] numbers, int target) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < numbers.length; i++) {
            map.put(numbers[i], i + 1);
        }
        for (int i = 0; i < numbers.length; i++) {
            int diff = target - numbers[i];
            if (map.containsKey(diff)) {
                int[] res = {i + 1, map.get(diff)};
                return res;
            }
        }
        return null;
    }

    public int[] betterMethod(int[] numbers, int target) {
        int i = 0, j = numbers.length - 1;
        while (numbers[i] + numbers[j] != target) {
            if (numbers[i] + numbers[j] > target) j--;
            else i++;
        }
        return new int[] {i + 1, j + 1};
    }

    public static void main(String[] args) {
        int[] numbers = {2, 7, 11, 15};
        int target = 9;
        System.out.println(Arrays.toString(new TwoSum2().twoSum(numbers, target)));
        System.out.println(Arrays.toString(new TwoSum2().betterMethod(numbers, target)));
    }
}
